#include "levelactorpatternslistwidget.h"
#include "modes/leveleditormode.h"
#include "application.h"
#include "document.h"
#include "gameObjects/visualobject.h"
#include "gameObjects/actor.h"
#include "utils.h"

LevelActorPatternsListWidget::LevelActorPatternsListWidget(QWidget *parent)
	: QListWidget(parent)
{
	setIconSize(QSize(64, 64));

	connect(this, &QListWidget::itemSelectionChanged, 
		this, &LevelActorPatternsListWidget::onItemSelectionChanged);
}

void LevelActorPatternsListWidget::populateView()
{
	clear();
	ACQUIRE_DOC();

	if(doc)
	{
		const Document::Actors& listActors = doc->actors();

		int index = 0;
		foreach(QPointer<AbstractGameObject> act, listActors)
		{
			LevelActorPatternsListWidgetItem* pItem = new LevelActorPatternsListWidgetItem;
			pItem->object = act;
			pItem->setText(act->name());

			// generate little tumbnail
			const Actor::VisualObjects& visualObjectList = qobject_cast<Actor*>(act)->visualObjects();
			QPixmap tumbnail(64, 64);

			if(visualObjectList.size() &&
				!qobject_cast<VisualObject*>(visualObjectList.first())->imageData().image().isNull())
			{
				QPointer<VisualObject> firstVisualObject = qobject_cast<VisualObject*>(visualObjectList.first());
				const QImage& image = firstVisualObject->imageData().image();
				QRect frameRect;

				if(firstVisualObject->isAnimation())
				{
					frameRect = firstVisualObject->frames().first();
				}

				tumbnail = generateImageTumbnail(image, 64, 64, frameRect);
			}
			else
			{
				tumbnail.fill(Qt::darkGray);
			}
			pItem->setIcon(QIcon(tumbnail));
			addItem(pItem);

			if(index++ == 0)
			{
				pItem->setSelected(true);
			}
		}
	}
}

void LevelActorPatternsListWidget::setLevelEditorMode( QPointer<Modes::EditorMode> lem )
{
	QPointer<Modes::LevelEditorMode> pMode = qobject_cast<Modes::LevelEditorMode*>(lem);
	connect(pMode, &Modes::LevelEditorMode::populateActorPatternsView, 
		this, &LevelActorPatternsListWidget::populateView);
	connect(this, &LevelActorPatternsListWidget::selectedActorPatternChanged, 
		pMode, &Modes::LevelEditorMode::onSelectedActorPatternChanged);
}

void LevelActorPatternsListWidget::onItemSelectionChanged()
{
	QList<QListWidgetItem*> selItems = selectedItems();
	Q_ASSERT(selItems.size() < 2);

	QPointer<AbstractGameObject> result;

	if(selItems.size())
	{
		LevelActorPatternsListWidgetItem* pItem = static_cast<LevelActorPatternsListWidgetItem*>(selItems.first());
		Q_ASSERT(pItem);
		result = pItem->object;
	}

	emit selectedActorPatternChanged(result);
}
